#!/bin/sh
# Author: Yuan Li
# Titile: lab8 for the 15123 summer
# Date: Aug 23 2011


#clean up 
cleanFiles()
{
rm -f submissions.tar
rm -rf submissions
}


#get the submission files
getSubmissions()
{
wget http://www.cs.cmu.edu/~thoffman/15-123/lab-XC/submissions.tar
tar xvf submissions.tar
}

#process a submission
doProcess()
{
# create folder according to the andrewID
ID=${1%.c}
mkdir ${ID}
# put c file input that folder
cp $1 ${ID}/
# get lib, input and correct files
cd ${ID}
wget http://www.cs.cmu.edu/~thoffman/15-123/lab-XC/getline.h
wget http://www.cs.cmu.edu/~thoffman/15-123/lab-XC/getline.c
wget http://www.cs.cmu.edu/~thoffman/15-123/lab-XC/input.txt
wget http://www.cs.cmu.edu/~thoffman/15-123/lab-XC/correctOutput.txt
# get static compilation info
gcc -ansi -pedantic -W -Wall -Wextra -O2 *.c 2>&1 | grep "warning"
# get warning info
if [ $? = "0" ];then
	WARN=" with warnings"
else
	WARN=""
fi
# get a.out info
ls | grep "a.out"
if [ $? = "0" ];then
	COMPILE="compilation successful${WARN}"
	COM="true"
else
	COMPILE="compilation unsuccessful"
	COM="false"
fi
#Get runtime info
# compare result
if [ $COM = "false" ];then
	OUTPUT="output N/A"
	OUT="false"
else
	./a.out input.txt > output.txt
	diff -a -b -B output.txt correctOutput.txt | grep "[<>]"
	if [ $? != "0" ];then
		OUTPUT="output correct"
		OUT="true"
		
	else
		OUTPUT="output incorrect"
		OUT="true"
	fi
fi


# check leaks
if [ $OUT != "true" ];then
	LEAKS="leaks N/A"
else
	LEAKS=0
	LEAKS=$(\
	valgrind --tool=memcheck --leak-check=yes \
		--show-reachable=yes --num-callers=20 --track-fds=yes \
		./a.out input.txt 2>&1 | grep '[a-z]*ly lost:' | \
		awk '{if(NR==1) total = $4}\
			{if(NR>=2) total = $4 + total}\
			{if(NR==3) print total}'
			)
	if [ $LEAKS != "" ];then
		LEAKS="leaks ${LEAKS} bytes"
	else
		LEAKS="leaks N/A"
	fi
fi

cd ..
echo ${ID}, ${COMPILE}, ${OUTPUT}, ${LEAKS} >> graded.txt

}



# My Main Routine
getSubmissions

cd ./submissions

for FILE in *.c
do
	doProcess ${FILE}
done
cd ..
clear
cat ./submissions/graded.txt
cleanFiles


##################
